import request from '@/utils/request';
import { Product } from '@/models/product';
import { setPropertyUndefinedIfEmpty } from '@/utils/utils';

const prefix = '/products';

export async function list(payload: Product): Promise<Product[]> {
  const productCategoryIds = payload?.productCategoryIds || undefined;
  console.log(payload);
  return request(prefix, {
    params: setPropertyUndefinedIfEmpty({
      ...payload,
      productCategoryId: productCategoryIds
        ? productCategoryIds[productCategoryIds.length - 1]
        : undefined,
    }),
  });
}

export async function create(formData: any): Promise<any> {
  return request(`${prefix}/create`, {
    method: 'POST',
    data: formData,
  });
}

export async function add(product: Product): Promise<any> {
  return request(prefix, {
    method: 'POST',
    data: product,
  });
}

export async function update(payload: Product): Promise<number> {
  return request(`${prefix}/${payload.id}`, {
    method: 'PUT',
    data: payload,
  });
}

export async function remove(id: number): Promise<any> {
  return request(`${prefix}/${id}`, {
    method: 'DELETE',
  });
}
